package com.example.micro.netty.server.thread;

/**
 * 交替打印
 * notify之后必须要执行完后面的逻辑后，才能释放锁
 *
 * @author Code Farmer
 * @create 2020/10/7 5:03 下午
 */
public class AlternatePrint {

    private static final Object object = new Object();

    public static class ThreadA extends Thread {
        @Override
        public void run() {
            synchronized (object) {
                for (int i = 0; ; i += 2) {
                    object.notify();
                    System.out.println(Thread.currentThread().getName() + ":" + i);

                    try {
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static class ThreadB extends Thread {
        @Override
        public void run() {
            synchronized (object) {
                for (int i = 1; ; i += 2) {
                    object.notify();
                    System.out.println(Thread.currentThread().getName() + ":" + i);

                    try {
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }

    public static void main(String[] args) {
        ThreadA threadA = new ThreadA();
        ThreadB threadB = new ThreadB();
        threadA.start();
        threadB.start();
    }

}
